<template>
  <a-modal
    v-model="visible"
    :title="title"
    @ok="addClassify"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
  >
    <a-form-model ref="textForm" :model="form" v-bind="layout" :rules="rules">
      <a-form-model-item label="填写分类名称" prop="name">
        <a-input
          v-model="form.name"
          :maxLength="6"
          placeholder="输入分类名称限1-6个汉字"
        />
      </a-form-model-item>
      <a-form-model-item label="排序" prop="sort">
        <a-input-number
          :precision="0"
          style="width: 236px"
          v-model="form.sort"
          placeholder="输入整数，数字越大排列越靠后"
        />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
export default {
  props: {
    record: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      visible: false,
      form: {
        name: "",
        sort: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入分类名称限1-6个汉字",
            trigger: "blur",
          },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 12 },
      },
      confirmLoading: false,
      title: "新增分类",
    };
  },
  watch: {
    visible: function (val, oldVal) {
      if (!val) {
        this.title = "新增分类";
        this.form = {
          id: "",
          name: "",
          sort: "",
        };
        this.confirmLoading = false;
        this.$refs.textForm.resetFields();
      } else if (this.record?.id) {
        this.title = "编辑分类";
        this.form.name = this.record?.name;
        this.form.sort = this.record?.sort;
        this.form.id = this.record?.id;
      }
    },
  },
  methods: {
    addClassify() {
      this.$refs.textForm.validate((valid) => {
        if (valid) {
          this.handleOk();
        }
      });
    },
    handleCancel() {
      this.visible = false;
    },
    async handleOk() {
      this.confirmLoading = true;
      try {
        if (this.form.id) {
          await this.$post(
            "goldenhome/gh/poster_admin/copywriting/category/update",
            { ...this.form }
          );
        } else {
          await this.$post(
            "goldenhome/gh/poster_admin/copywriting/category/add",
            { ...this.form }
          );
        }
        this.handleCancel();
        this.$emit("refresh");
      } catch (e) {
        console.log(e);
        this.confirmLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>
